<script setup>
import { computed, reactive, ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { debounce } from 'radash'
import { PageUtil } from '../../utils/PageUtil'
import { useDictionaryStore } from '../../store/DictionaryStore'
import { useLoading } from '../../store/LoadingStore'
import LoadingFooter from '../../components/LoadingFooter.vue'
import DialogItemList from './coms/DialogItemList.vue'
import SearchInput from '../../components/SearchInput.vue'
import { useDialogStore } from '../../store/DialogStore'

const loadingStore = useLoading()
const dictStore = useDictionaryStore()
const dialogStore = useDialogStore()
const multiple = computed(() => {
  const { multiple = true } = dialogParams
  return multiple
})

const valueKey = computed(() => {
  const { valueKey = false } = dialogParams
  return valueKey
})

const dialogParams = reactive({})
const queryParams = reactive({
  limit: 1,
  size: 20
})

const dict = reactive({})

const dataColumns = ref([
  { label: '存货编码', prop: 'bii_code' },
  { label: '存货名称', prop: 'bii_name' },
  { label: '规格型号', prop: 'bii_spec' },
  { label: '存货单位', prop: 'bu_name' },
  { label: '领料数量', prop: 'bii_count' },
  // { label: '单价', prop: 'price' },
  // { label: '金额(元)', prop: 'amount' },
  // { label: '库存', prop: 'stock_qty' },
  { label: '备注', prop: 'remark' }
])

const list = reactive({
  rows: [],
  total: 0,
  selection: []
})

const queryList = function() {
  debounceQuery()
}

const searchList = function() {
  loadingStore.NEW_LIST()
  queryParams.limit = 1
  queryList()
}
const debounceQuery = debounce({ delay: 300 }, () => {
  loadingStore.SET_LOADING()
  const { iioBussId,bii_type } = dialogParams

  // dialogStore
    // .getMIDetail({
    //   id: iioBussId
    // })
   dictStore
    .getBiiList({
      ...queryParams,
      bii_type,
      bii_type_list:"1"
    })
    .then((res) => {
      // let { stores_goods_detail: Rows = [] } = res || {}
      let { Rows = [],Total = 0 } = res || {}
      if (loadingStore.isLoadMore(list.rows, Total)) {
        console.log('concat')
        list.rows = list.rows.concat(Rows)
      } else {
        console.log('new rows')
        list.rows = Rows
      }
	  list.total = Total
      loadingStore.FINISH_ALL()
      uni.stopPullDownRefresh()
    })
})

const loadMore = function() {
  if (loadingStore.ILOADING) {
    return
  }
  const { total = 0, rows = [] } = list
  if (loadingStore.hasMore(rows, total)) {
    queryParams.limit += 1
    debounceQuery()
  }
}

const confirm = function() {
  const { valueKey } = dialogParams || {}
  const data = []
  const { selection = [], rows = [] } = list || {}
  rows.map((item) => {
    if (selection.includes(item['bii_id'])) {
      data.push(item)
    }
  })
  PageUtil.emitPageEvent(data)
  PageUtil.back()
}

const onChecked = function(e) {
  const {
    detail: { value }
  } = e
  list.selection = value
}

const onSelected = function(e) {
  const {
    detail: { value }
  } = e
  list.selection = [value]
  confirm()
}

onLoad((params) => {
  let { row, __eventId__, valueKey } = PageUtil.parseParam(params)
  dialogParams['__eventId__'] = __eventId__
  dialogParams['valueKey'] = valueKey

  Object.entries(row).map(([k, v]) => {
    dialogParams[k] = v
  })
  console.log('[biiDialog] params->', dialogParams)
  searchList()
})

onReachBottom(() => {
  loadMore()
})
</script>

<template>
  <div class="page-warp h-f bg-grey-200">
<!--    <div class="header-warp">-->
<!--      <div class="sticky-headers sticky bg-white search">-->
<!--        <div class="col">-->
<!--          <search-input v-model="queryParams.keyword" @search="searchList" :more="false"/>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->

    <div class="m-content">
      <div class="m-warp">
        <checkbox-group @change="onChecked" v-if="multiple">
          <dialog-item-list
            :columns="dataColumns"
            :data="list.rows"
            :selected="list.selection"
            row-key="bii_id"
          >
            <template #type="{ value }">
              <checkbox class="checkbox" :value="value" />
            </template>
          </dialog-item-list>
        </checkbox-group>

        <radio-group @change="onSelected" v-else>
          <dialog-item-list
            :columns="dataColumns"
            :data="list.rows"
            :selected="list.selection"
            row-key="bii_id"
          >
            <template #type="{ value }">
              <radio class="radio" :value="value" />
            </template>
          </dialog-item-list>
        </radio-group>

        <LoadingFooter
          :data="list.rows"
          :total="list.total"
          :loading="loadingStore.ILOADING"
          @load="loadMore"
        />
      </div>
    </div>

    <div class="form-footer" v-if="multiple">
      <div class="footer-warp">
        <div class="footer__btn">
          <div class="btn">
            <button
              class="uni-btn"
              type="primary"
              @click="confirm"
              :disabled="loadingStore.ILOADING"
              :loading="loadingStore.ILOADING"
            >
              确定
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/PageCommon.scss';
//@import '@/assets/dialogCommon.scss';

.page-warp {
  .header-warp {
    &:after {
      height: 70px;
    }
  }

  .value {
    font-size: 14px;
  }

  .m-content {
    .prod-footer {
      display: flex;
      align-items: center;
      justify-content: center;

      .footer-btn {
        display: flex;
        align-items: center;
      }
    }
  }

  .form-footer {
    height: 65px;
  }
}
</style>
